package com.itqianfeng.dao;

import com.itqianfeng.dao.utils.DbHelper;
import com.itqianfeng.mapper.BaseMapping;
import com.itqianfeng.pojo.Customer;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BaseDao<T> implements DbHelper {
    Connection con = null;
    PreparedStatement ps = null;


    public List<T> findAll(String sql, BaseMapping<T> map) throws SQLException {

        List<T> list = new ArrayList<>();
        ResultSet rs = null;
        try {
            // 创建连接
            con = getConnection();
            // 准备SQL
            // String sql = "select * from customers";
            // 打包  ， 编译
            ps = con.prepareStatement(sql);
            // 执行
            // 获取结果
            rs = ps.executeQuery();
            // 处理数据
            while (rs.next()) {

                list.add(map.mapping(rs));

                // System.out.println("顾客ID: " + customerId + "\t顾客姓名: " + firstName
                //         + "\t\t顾客生日: " + birthDate + "\t\t顾客积分: " + points);
            }

        } finally {
            // 关闭连接资源
            close(con, ps, rs);
        }
        return list;

    }

    public T findById(String sql , int id , BaseMapping<T> map) throws Exception {
        // String sql = "select * from customers where customer_id = " + id;

        T bean = null;
        ResultSet rs = null;
        try {
            con = getConnection();
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery(sql);


            if (rs.next()) {
                // 如果有数据，这个时候，rs会指向一行记录
                // 我们操作数据的时候，只能让指针来读取某一列的信息
                // int customerId = resultSet.getInt("customer_id");


                bean  = map.mapping(rs);

                // System.out.println(customerId + ":" + firstName + ":" + birthDate + ":" + points);
            }
        } finally {
            close(con, ps, rs);
        }

        return bean;
    }

    public   void updateOrSave(String sql ,Object ...args) throws SQLException {
        // String sql = "update customers set  first_name = ? , last_name = ? ,birth_date = ? ," +
        //         "phone = ? , address = ?,city = ?,  state = ?, points = ? where customer_id =" + bean.getId();

        try{
            con = getConnection();
            ps = con.prepareStatement(sql);

            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1,args[i]);
            }
            ps.executeUpdate();

        }finally {
            close(con,ps,null);
        }

    }

    public  void deleteData(String sql ,int id) throws SQLException {

        // String sql = "delete from customers where customer_id = " + id;

        try{
            con = getConnection();
            ps = con.prepareStatement(sql);
            ps.setInt(1,id);
            ps.executeUpdate();
        }finally {
            close(con,ps,null);
        }

    }
}
